﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace QLFUI
{
    [ToolboxItem(true)]
    [DefaultEvent("Click")]
    public partial class ButtonEx : QLFControlBase, ITransparent
    {
        #region  enum

        public enum ButtonStyleEnum
        {
            XunLei,
            QQ,
            _360,
            Customer
        }

        /// <summary>
        /// 背景图片和文字的位置关系
        /// </summary>
        public enum ImageTextPositionEnum
        {
            ImageTop,
            ImageRight,
            ImageBottom,
            ImageLeft,
            None
        }

        #endregion

        #region 变量

        private readonly Timer mInAnimate;
        private readonly Timer mOutAnimate;
        private int _animateSpeed = 12;

        private Color _bottomHighlight;
        private Color _bottomHighlightHover = Color.Transparent;
        private Color _bottomHighlightNormal = Color.Transparent;
        private Color _bottomHighlightPress = Color.Transparent;

        private Image _image;
        private Image _imageHover;
        private Image _imageNormal;
        private Image _imagePress;

        private Color _topHighlight;
        private Color _topHighlightHover = Color.Transparent;
        private Color _topHighlightNormal = Color.Transparent;
        private Color _topHighlightPress = Color.Transparent;

        private ButtonStyleEnum buttonStyle = ButtonStyleEnum.XunLei;
        private ContentAlignment _textAlignment = ContentAlignment.MiddleCenter;
        private ImageTextPositionEnum imageTextPosition = ImageTextPositionEnum.None;
        private int imageTextScale = 50;
        private int mAlpha;

        #endregion

        #region 构造函数

        public ButtonEx()
        {
            InitializeComponent();
            mInAnimate = new Timer { Interval = 20 };
            mInAnimate.Tick += mInAnimate_Tick;
            mOutAnimate = new Timer { Interval = 20 };
            mOutAnimate.Tick += mOutAnimate_Tick;

            #region 属性预设值

            Width = 85;
            Height = 27;
            BackColorMode = LinearGradientMode.Vertical;
            ButtonStyle = ButtonStyleEnum.QQ;
            BorderRadius.LeftBottom = BorderRadius.LeftTop =
            BorderRadius.RightBottom = BorderRadius.RightTop = 3;

            #endregion
        }

        #endregion

        #region 属性

        [DefaultValue(ContentAlignment.MiddleCenter)]
        [Category("2_QLFUI_Other"), Description("文字的对齐方式")]
        public ContentAlignment TextAlignment
        {
            get { return _textAlignment; }
            set
            {
                _textAlignment = value;
                Invalidate();
            }
        }

        /// <summary>
        /// 控件普通三态之间颜色过渡动画速度（100为没有动画）
        /// </summary>
        [Category("2_QLFUI_Other"), Description("动画速度(1-100)")]
        public int AnimateSpeed
        {
            get { return _animateSpeed; }
            set
            {
                if (value <= 0 || value > 100)
                {
                    MessageBox.Show("速度必须在1-100之间");
                    return;
                }
                _animateSpeed = value;
            }
        }

        [Category("2_QLFUI_Other"), Description("按钮样式")]
        public ButtonStyleEnum ButtonStyle
        {
            get { return buttonStyle; }
            set
            {
                buttonStyle = value;

                switch (buttonStyle)
                {
                    case ButtonStyleEnum.XunLei:
                        BorderColor = Color.FromArgb(186, 197, 207);
                        InnerBorderColor = Color.Transparent;
                        BackColorStart = Color.FromArgb(238, 241, 243);
                        BackColorEnd = Color.FromArgb(225, 230, 235);

                        BorderColorHover = Color.FromArgb(146, 159, 173);
                        InnerBorderColorHover = Color.Transparent;
                        BackColorStartHover = Color.FromArgb(216, 222, 227);
                        BackColorEndHover = Color.FromArgb(205, 212, 217);

                        BorderColorPress = Color.FromArgb(147, 159, 143);
                        InnerBorderColorPress = Color.Transparent;
                        BackColorStartPress = Color.FromArgb(199, 205, 211);
                        BackColorEndPress = Color.FromArgb(187, 195, 200);
                        break;

                    case ButtonStyleEnum.QQ:
                        BorderColor = Color.FromArgb(159, 172, 186);
                        InnerBorderColor = Color.FromArgb(247, 249, 251);
                        BackColorStart = Color.FromArgb(253, 253, 254);
                        BackColorEnd = Color.FromArgb(218, 229, 233);

                        BorderColorHover = Color.FromArgb(66, 126, 174);
                        InnerBorderColorHover = Color.FromArgb(86, 209, 255);
                        BackColorStartHover = Color.FromArgb(251, 252, 253);
                        BackColorEndHover = Color.FromArgb(220, 230, 234);

                        BorderColorPress = Color.FromArgb(163, 175, 188);
                        InnerBorderColorPress = Color.FromArgb(239, 243, 246);
                        BackColorStartPress = Color.FromArgb(216, 227, 232);
                        BackColorEndPress = Color.FromArgb(251, 252, 253);
                        break;

                    case ButtonStyleEnum._360:
                        BorderColor = Color.FromArgb(214, 214, 214);
                        InnerBorderColor = Color.Transparent;
                        BackColorStart = Color.FromArgb(255, 255, 255);
                        BackColorEnd = Color.FromArgb(212, 228, 235);

                        BorderColorHover = Color.FromArgb(50, 110, 176);
                        InnerBorderColorHover = Color.Transparent;
                        BackColorStartHover = Color.FromArgb(251, 252, 253);
                        BackColorEndHover = Color.FromArgb(220, 230, 234);

                        BorderColorPress = Color.FromArgb(176, 185, 196);
                        InnerBorderColorPress = Color.FromArgb(233, 234, 234);
                        BackColorStartPress = Color.FromArgb(211, 212, 213);
                        BackColorEndPress = Color.FromArgb(220, 224, 226);
                        break;
                }
            }
        }

        //基本控件里面该属性默认为隐藏状态
        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
         Bindable(true),
         DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)
        ]
        public override string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        [Browsable(true)]
        public new ImageLayout BackgroundImageLayout
        {
            get { return base.BackgroundImageLayout; }
            set { base.BackgroundImageLayout = value; }
        }

        [Category("2_QLFUI_Other"), Description("背景图片和文字的位置关系")]
        public ImageTextPositionEnum ImageTextPosition
        {
            get { return imageTextPosition; }
            set
            {
                imageTextPosition = value;

                if (DesignMode)
                {
                    Validate();
                }
            }
        }

        [Category("2_QLFUI_Other"), Description("ImageTextPosition属性不为None时，图像占整个控件空间的比例（1-99）")]
        public int ImageTextScale
        {
            get { return imageTextScale; }
            set
            {
                if (value < 1 || value > 99)
                {
                    if (DesignMode)
                    {
                        MessageBox.Show(@"属性错误，应该为1-99之间的数值");
                    }
                    return;
                }
                imageTextScale = value;

                SetNormalState();
            }
        }

        #region - 正常状态 -

        [Category("1_QLFUI"), Description("顶部高亮")]
        public Color TopHighlightNormal
        {
            get { return _topHighlightNormal; }
            set
            {
                _topHighlightNormal = value;
                SetNormalState();
            }
        }

        [Category("1_QLFUI"), Description("底部高亮")]
        public Color BottomHighlightNormal
        {
            get { return _bottomHighlightNormal; }
            set
            {
                _bottomHighlightNormal = value;
                SetNormalState();
            }
        }

        [Category("1_QLFUI"), Description("背景图片")]
        public Image ImageNormal
        {
            get { return _imageNormal; }
            set
            {
                _imageNormal = value;
                _image = _imageNormal;
                Invalidate();
            }
        }

        #endregion

        #region - 悬停状态 -

        [Category("1_QLFUI_Hover"), Description("顶部高亮")]
        public Color TopHighlightHover
        {
            get { return _topHighlightHover; }
            set { _topHighlightHover = value; }
        }

        [Category("1_QLFUI_Hover"), Description("底部高亮")]
        public Color BottomHighlightHover
        {
            get { return _bottomHighlightHover; }
            set { _bottomHighlightHover = value; }
        }

        [Category("1_QLFUI_Hover"), Description("悬停时的背景图片")]
        public Image ImageHover
        {
            get { return _imageHover; }
            set
            {
                _imageHover = value;
                Invalidate();
            }
        }

        #endregion

        #region - 按下状态 -

        [Category("1_QLFUI_Press"), Description("鼠标按下时的顶部高亮")]
        public Color TopHighlightPress
        {
            get { return _topHighlightPress; }
            set { _topHighlightPress = value; }
        }

        [Category("1_QLFUI_Press"), Description("按下状态下底部高亮")]
        public Color BottomHighlightPress
        {
            get { return _bottomHighlightPress; }
            set { _bottomHighlightPress = value; }
        }

        [Category("1_QLFUI_Press"), Description("按下状态下背景图片")]
        public Image ImagePress
        {
            get { return _imagePress; }
            set
            {
                _imagePress = value;
                Invalidate();
            }
        }

        #endregion

        #region 需要隐藏的属性



        [Browsable(false)]
        public new BorderStyle BorderStyle
        {
            get { return base.BorderStyle; }
            set { base.BorderStyle = value; }
        }

        [Browsable(false)]
        public new Image BackgroundImage
        {
            get { return base.BackgroundImage; }
            set { base.BackgroundImage = value; }
        }


        #endregion

        #endregion

        #region 事件

        private void ButtonEx_Load(object sender, EventArgs e)
        {
            SetNormalState();
        }

        private void ButtonEx_MouseEnter(object sender, EventArgs e)
        {
            mOutAnimate.Stop();

            mAlpha = 0;
            mInAnimate.Start();

            _image = ImageHover;
        }

        private void ButtonEx_MouseLeave(object sender, EventArgs e)
        {
            mInAnimate.Stop();

            mAlpha = 0;
            mOutAnimate.Start();

            _image = ImageNormal;
        }

        private void ButtonEx_MouseDown(object sender, MouseEventArgs e)
        {
            SetPressState();

            fz();

            _image = ImagePress;
        }

        private void ButtonEx_MouseUp(object sender, MouseEventArgs e)
        {
            SetHoverState();

            _image = ImageHover;
        }

        protected override void OnEnabledChanged(EventArgs e)
        {
            base.OnEnabledChanged(e);

            if (!Enabled)
            {
                currentBorderColor = BorderColorUnEnable;
                currentInnerBorderColor = InnerBorderColorUnEnable;
                currentBackColorStart = BackColorStartUnEnable;
                currentBackColorEnd = BackColorEndUnEnable;
                ForeColor = ForeColorUnEnable;
            }

            Invalidate();
            NotifyUpdate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            if (!IsEnableTransparent())
            {
                //这里一定要用0,0如果使用e.ClipRectangle那么当按钮被遮盖
                //后，就会出现难看的重绘大小
                Draw(g, new Rectangle(0, 0, Width, Height));
            }

            base.OnPaint(e);
        }

        private void mOutAnimate_Tick(object sender, EventArgs e)
        {
            if (mAlpha + AnimateSpeed >= 100)
            {
                mAlpha = 100;
                mOutAnimate.Stop();
            }
            else
            {
                mAlpha += AnimateSpeed;
            }

            //如果目标颜色为透明色，则改变取色方式
            int a = 255 - (int)(mAlpha * 2.55);
            if (BackColorStart == Color.Transparent)
            {
                if (BackColorStartHover != Color.Transparent)
                {
                    currentBackColorStart = Color.FromArgb(a, BackColorStartHover);
                }
                else
                {
                    //首尾都是透明色则直接不显示
                    currentBackColorStart = Color.Transparent;
                }
            }
            else
            {
                currentBackColorStart = GetIntermediateColor(BackColorStartHover, BackColorStart, mAlpha);
            }
            currentBackColorEnd = BackColorEnd;

            //if (BackColorEnd == Color.Transparent)
            //{
            //    currentBackColorEnd = Color.FromArgb(a, backColorEndHover);
            //}
            //else
            //{
            //    currentBackColorEnd = GetIntermediateColor(backColorEndHover, BackColorEnd, mAlpha);
            //}

            if (BorderColor == Color.Transparent)
            {
                currentBorderColor = Color.Transparent;
            }
            else
            {
                currentBorderColor = GetIntermediateColor(BorderColorHover, BorderColor, mAlpha);
            }

            if (InnerBorderColor == Color.Transparent)
            {
                currentInnerBorderColor = Color.Transparent;
            }
            else
            {
                currentInnerBorderColor = GetIntermediateColor(InnerBorderColorHover, InnerBorderColor, mAlpha);
            }

            if (TopHighlightNormal == Color.Transparent)
            {
                _topHighlight = Color.Transparent;
                //_topHighlight = Color.FromArgb(a, TopHighlightHover);
            }
            else
            {
                _topHighlight = GetIntermediateColor(TopHighlightHover, TopHighlightNormal, mAlpha);
            }

            if (BottomHighlightNormal == Color.Transparent)
            {
                // _bottomHighlight = Color.FromArgb(a, BottomHighlightHover);
                _bottomHighlight = Color.Transparent;
            }
            else
            {
                _bottomHighlight = GetIntermediateColor(BottomHighlightHover, BottomHighlightNormal, mAlpha);
            }

            if (!IsEnableTransparent())
            {
                Invalidate();
            }
            else
            {
                NotifyUpdate();
            }
        }

        private void mInAnimate_Tick(object sender, EventArgs e)
        {
            if (mAlpha + AnimateSpeed >= 100)
            {
                mAlpha = 100;
                mInAnimate.Stop();
            }
            else
            {
                mAlpha += AnimateSpeed;
            }


            //如果目标颜色为透明色，则改变取色方式
            int a = 255 - (int)(mAlpha * 2.55);
            if (BackColorStartHover == Color.Transparent)
            {
                if (BackColorStart != Color.Transparent)  //当起始色不是透明时才向透明色渐变
                {
                    currentBackColorStart = Color.FromArgb(a, BackColorStart);
                }
                else
                {
                    currentBackColorStart = Color.Transparent;
                }
            }
            else
            {
                currentBackColorStart = GetIntermediateColor(BackColorStart, BackColorStartHover, mAlpha);
            }
            currentBackColorEnd = BackColorEndHover;

            if (BorderColorHover == Color.Transparent)
            {
                currentBorderColor = Color.Transparent;
            }
            else
            {
                currentBorderColor = GetIntermediateColor(BorderColor, BorderColorHover, mAlpha);
            }

            if (InnerBorderColorHover == Color.Transparent)
            {
                currentInnerBorderColor = Color.Transparent;
            }
            else
            {
                currentInnerBorderColor = GetIntermediateColor(InnerBorderColor, InnerBorderColorHover, mAlpha);
            }

            if (TopHighlightHover == Color.Transparent)
            {
                _topHighlight = Color.Transparent;
            }
            else
            {
                _topHighlight = GetIntermediateColor(TopHighlightNormal, TopHighlightHover, mAlpha);
            }

            if (BottomHighlightHover == Color.Transparent)
            {
                _bottomHighlight = Color.Transparent;
            }
            else
            {
                _bottomHighlight = GetIntermediateColor(BottomHighlightNormal, BottomHighlightHover, mAlpha);
            }

            if (!IsEnableTransparent())
            {
                Invalidate();
            }
            else
            {
                NotifyUpdate();
            }
        }

        #endregion

        #region 帮助方法

        private StringFormat StringFormatAlignment(ContentAlignment textalign)
        {
            var sf = new StringFormat();
            switch (textalign)
            {
                case ContentAlignment.TopLeft:
                case ContentAlignment.TopCenter:
                case ContentAlignment.TopRight:
                    sf.LineAlignment = StringAlignment.Near;
                    break;
                case ContentAlignment.MiddleLeft:
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.MiddleRight:
                    sf.LineAlignment = StringAlignment.Center;
                    break;
                case ContentAlignment.BottomLeft:
                case ContentAlignment.BottomCenter:
                case ContentAlignment.BottomRight:
                    sf.LineAlignment = StringAlignment.Far;
                    break;
            }
            switch (textalign)
            {
                case ContentAlignment.TopLeft:
                case ContentAlignment.MiddleLeft:
                case ContentAlignment.BottomLeft:
                    sf.Alignment = StringAlignment.Near;
                    break;
                case ContentAlignment.TopCenter:
                case ContentAlignment.MiddleCenter:
                case ContentAlignment.BottomCenter:
                    sf.Alignment = StringAlignment.Center;
                    break;
                case ContentAlignment.TopRight:
                case ContentAlignment.MiddleRight:
                case ContentAlignment.BottomRight:
                    sf.Alignment = StringAlignment.Far;
                    break;
            }
            return sf;
        }

        protected override void SetNormalState()
        {
            base.SetNormalState();

            _topHighlight = TopHighlightNormal;
            _bottomHighlight = BottomHighlightNormal;
            _image = ImageNormal;

            Invalidate();
            NotifyUpdate();
        }

        protected override void SetHoverState()
        {
            base.SetHoverState();

            _topHighlight = TopHighlightHover;
            _bottomHighlight = BottomHighlightHover;
            _image = ImageHover;


            Invalidate();
            NotifyUpdate();
        }

        protected override void SetPressState()
        {
            base.SetPressState();

            _topHighlight = TopHighlightPress;
            _bottomHighlight = BottomHighlightPress;
            _image = ImagePress;

            Invalidate();
            NotifyUpdate();
        }

        private void Draw(Graphics g, Rectangle rectangle)
        {
            DrawBackColor(g, rectangle);

            #region 顶部高亮

            int topHighlightWidth = 1;
            if (rectangle.Width > 3)
            {
                topHighlightWidth = rectangle.Width - 3;
            }
            var tr = new Rectangle(rectangle.X, rectangle.Y, topHighlightWidth, 15);
            GraphicsPath tp = DrawRoundRect(tr, 2, 2, 0, 0);

            g.SetClip(tp);
            var tg = new LinearGradientBrush(tr, _topHighlight,
                                             Color.Transparent,
                                             LinearGradientMode.Vertical);
            g.FillPath(tg, tp);
            g.ResetClip();

            #endregion

            #region 底部高亮

            //Rectangle br = new Rectangle(1, this.Height - 8, this.Width - 3, 6);
            //GraphicsPath bp = DrawHelper.DrawRoundRect(br, 0, 0, 2, 2);

            //g.SetClip(bp);
            //LinearGradientBrush bg = new LinearGradientBrush(br, _backgroundColor,
            //                                                 _bottomHighlight,
            //                                                 LinearGradientMode.Vertical);
            //g.FillPath(bg, bp);
            //g.ResetClip();


            using (var glow = new GraphicsPath())
            {
                glow.AddEllipse(rectangle.X - 15, rectangle.Y + Height / 2, Width + 15, Height + 15);
                using (var gl = new PathGradientBrush(glow))
                {
                    //将底部高亮限制在下半部分的矩形中，否则超过按钮的部分在透明状态下会画出来
                    g.SetClip(new Rectangle(rectangle.X, rectangle.Y + Height/2, Width, Height/2));

                    gl.CenterColor = _bottomHighlight;
                    gl.SurroundColors = new[] { Color.FromArgb(0, _bottomHighlight) };
                    g.FillPath(gl, glow);
                    g.ResetClip();
                }
            }

            #endregion

            DrawBorder(g, rectangle);
            DrawInnerBorder(g, rectangle);

            #region 图像

            if (_image != null)
            {
                Rectangle imageRect = rectangle;
                switch (imageTextPosition)
                {
                    case ImageTextPositionEnum.ImageTop:
                        imageRect.Height = Height * ImageTextScale / 100;
                        break;

                    case ImageTextPositionEnum.ImageRight:
                        imageRect.Width = Width * ImageTextScale / 100;
                        imageRect.X = Width - imageRect.Width;
                        break;

                    case ImageTextPositionEnum.ImageBottom:
                        imageRect.Height = Height * ImageTextScale / 100;
                        imageRect.Y = Height - imageRect.Height;
                        break;

                    case ImageTextPositionEnum.ImageLeft:
                        imageRect.Width = Width * ImageTextScale / 100;
                        break;
                }

                DrawBackgroundImage(g, _image, BackgroundImageLayout, imageRect, new Point(0, 0), RightToLeft);
            }

            #endregion

            #region 文字

            StringFormat sf = StringFormatAlignment(TextAlignment);

            Rectangle r = rectangle;
            switch (imageTextPosition)
            {
                case ImageTextPositionEnum.ImageTop:
                    r = new Rectangle(0, Height * ImageTextScale / 100, Width, Height - Height * ImageTextScale / 100);
                    break;

                case ImageTextPositionEnum.ImageRight:
                    r = new Rectangle(0, 0, Width - Width * ImageTextScale / 100, Height);
                    break;

                case ImageTextPositionEnum.ImageBottom:
                    r = new Rectangle(0, 0, Width, Height - Height * ImageTextScale / 100);
                    break;

                case ImageTextPositionEnum.ImageLeft:
                    r = new Rectangle(Width * ImageTextScale / 100, 0, Width - Width * ImageTextScale / 100, Height);
                    break;
            }

            g.DrawString(Text, Font, new SolidBrush(ForeColor), r, sf);

            #endregion
        }

        //一下两个方法摘自.net framework源码
        private void DrawBackgroundImage(Graphics g, Image backgroundImage,
                                         ImageLayout backgroundImageLayout, Rectangle imgRect,
                                         Point scrollOffset, RightToLeft rightToLeft)
        {
            if (g == null) throw new ArgumentNullException("g");
            if (backgroundImageLayout == ImageLayout.Tile)
            {
                using (var textureBrush = new TextureBrush(backgroundImage, WrapMode.Tile))
                {
                    if (scrollOffset != Point.Empty)
                    {
                        Matrix transform = textureBrush.Transform;
                        transform.Translate(scrollOffset.X, scrollOffset.Y);
                        textureBrush.Transform = transform;
                    }
                    g.FillRectangle(textureBrush, imgRect);
                }
            }
            else
            {
                Rectangle re = new Rectangle(0, 0, imgRect.Width, imgRect.Height);
                Rectangle rectangle1 = CalculateBackgroundImageRectangle(re, backgroundImage, backgroundImageLayout);
                rectangle1.X += imgRect.X;  //真正的位置应该加上偏移量
                rectangle1.Y += imgRect.Y;

                if (rightToLeft == RightToLeft.Yes && backgroundImageLayout == ImageLayout.None)
                {
                    rectangle1.X += imgRect.Width - rectangle1.Width;
                }
                //using (var solidBrush = new SolidBrush(backColor))
                //{
                //    g.FillRectangle(solidBrush, imgRect);
                //}
                if (!imgRect.Contains(rectangle1))
                {
                    if (backgroundImageLayout == ImageLayout.Stretch || backgroundImageLayout == ImageLayout.Zoom)
                    {
                        rectangle1.Intersect(imgRect);
                        g.DrawImage(backgroundImage, rectangle1);
                    }
                    else if (backgroundImageLayout == ImageLayout.None)
                    {
                        rectangle1.Offset(imgRect.Location);
                        Rectangle destRect = rectangle1;
                        destRect.Intersect(imgRect);
                        var rectangle2 = new Rectangle(Point.Empty, destRect.Size);
                        g.DrawImage(backgroundImage, destRect, rectangle2.X, rectangle2.Y, rectangle2.Width,
                                    rectangle2.Height, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        Rectangle destRect = rectangle1;
                        destRect.Intersect(imgRect);
                        var rectangle2 = new Rectangle(new Point(destRect.X - rectangle1.X, destRect.Y - rectangle1.Y),
                                                       destRect.Size);
                        g.DrawImage(backgroundImage, destRect, rectangle2.X, rectangle2.Y, rectangle2.Width,
                                    rectangle2.Height, GraphicsUnit.Pixel);
                    }
                }
                else
                {
                    var imageAttr = new ImageAttributes();
                    imageAttr.SetWrapMode(WrapMode.TileFlipXY);
                    g.DrawImage(backgroundImage, rectangle1, 0, 0, backgroundImage.Width, backgroundImage.Height,
                                GraphicsUnit.Pixel, imageAttr);
                    imageAttr.Dispose();
                }
            }
        }

        private Rectangle CalculateBackgroundImageRectangle(Rectangle bounds, Image backgroundImage,
                                                            ImageLayout imageLayout)
        {
            Rectangle rectangle = bounds;
            if (backgroundImage != null)
            {
                switch (imageLayout)
                {
                    case ImageLayout.None:
                        rectangle.Size = backgroundImage.Size;
                        break;
                    case ImageLayout.Center:
                        rectangle.Size = backgroundImage.Size;
                        Size boundSize = bounds.Size;
                        if (boundSize.Width > rectangle.Width)
                            rectangle.X = (boundSize.Width - rectangle.Width) / 2;
                        if (boundSize.Height > rectangle.Height)
                        {
                            rectangle.Y = (boundSize.Height - rectangle.Height) / 2;
                            break;
                        }
                        break;
                    case ImageLayout.Stretch:
                        rectangle.Size = bounds.Size;
                        break;
                    case ImageLayout.Zoom:
                        Size size2 = backgroundImage.Size;
                        float num1 = bounds.Width / (float)size2.Width;
                        float num2 = bounds.Height / (float)size2.Height;
                        if (num1 < (double)num2)
                        {
                            rectangle.Width = bounds.Width;
                            rectangle.Height = (int)(size2.Height * (double)num1 + 0.5);
                            if (bounds.Y >= 0)
                            {
                                rectangle.Y = (bounds.Height - rectangle.Height) / 2;
                                break;
                            }
                            else
                                break;
                        }
                        else
                        {
                            rectangle.Height = bounds.Height;
                            rectangle.Width = (int)(size2.Width * (double)num2 + 0.5);
                            if (bounds.X >= 0)
                            {
                                rectangle.X = (bounds.Width - rectangle.Width) / 2;
                                break;
                            }
                            else
                                break;
                        }
                }
            }
            return rectangle;
        }

        #endregion

        #region 实现接口

        public void Draw(Bitmap bitmap, Rectangle rect)
        {
            if (bitmap == null)
            {
                //throw new ArgumentNullException("bitmap null");
                return;
            }

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                Draw(g, new Rectangle(rect.X, rect.Y, rect.Width, rect.Height));

                //调用onpaint事件，防止用户实现了onpaint事件
                //比如说我们的功能按钮上面的x，-等等图案
                PaintEventArgs args = new PaintEventArgs(g, new Rectangle(Left, Top, Width, Height));
                OnPaint(args);
            }
        }

        #endregion
    }
}